new.html.erb
Price: <%= f.collection_select :price_ids, Price.all, :id,:name,prompt: true %> JD
In the controller:
def dress_attributes
dress_attributes = params.require(:dress).permit(:name,:email,:phone,:description,:image,:image2,[:price_ids: []})
end
In show.html.erb:
Price: <% #dress.prices.each do |s| %>
<%= s.name %>
<% end %>`
And the price doesn't show.
What's wrong when I change the collection_select to collection_checked_boxes? It works, but I want the collection_select.
You can pass multiple: true as html_options to collection_select as given below.
new.html.erb
Price: <%= f.collection_select :price_id, Price.all, :id,:name, {prompt: true}, {multiple: true} %> JD
In the controller
def dress_attributes
dress_attributes = params.require(:dress).permit(:name,:email,:phone,:description,:image,:image2,:price_id)
end
Then, in your controller, you can access price_id as params[:dress][:price_id] which will be an array of selected prices.
Related
I'm implementing a voting system where when the course is already upvoted/downvoted, clicking downvote/upvote will switch to that vote respectively and clicking again will delete that vote (similar to Reddit).
While voting and destroying vote perform correctly, I'm having trouble trying to update the vote with form_for and patch method, where the value of the vote_type returns nil
My Votes_Controller
class VotesController < ApplicationController
def create
#vote = Vote.new(secure_params)
#vote.course = Course.find(params[:course_id])
if #vote.save
respond_to do |format|
format.html { redirect_to :courses }
format.js
end
end
def update
vote = Vote.find_by(user: current_user)
vote.update_attribute(:vote_type, update_vote_params)
redirect_to :courses
end
def destroy
vote = Vote.find_by(user: current_user)
vote.destroy
redirect_to :courses, :notice => 'Unvoted!'
end
private
def secure_params
params.require(:vote).permit( :user_id, :vote_type )
end
def update_vote_params
params.require(:vote).permit(:vote_type)
end
end
My index.html.erb
<% if Vote.exists?(user: current_user) && Vote.find_by(user: current_user).vote_type.equal?(-1) %>
<%= form_for course.votes.build, url: course_vote_path(course, Vote.find_by(user: current_user).id), method: :patch do |f| %>
<%= f.hidden_field :vote_type, value: 1 %>
<%= f.submit 'Upvote', class: 'btn btn-default' %>
<% end %>
<% elsif Vote.exists?(user: current_user) && Vote.find_by(user: current_user).vote_type.equal?(1) %>
<%= form_for course.votes.build, url: course_vote_path(course, Vote.find_by(user: current_user).id), method: :delete do |f| %>
<%= f.submit "Upvote", class: 'btn btn-default' %>
<% end %>
<% else %>
<%= form_for course.votes.build, url: course_votes_path(course) do |f| %>
<%= f.hidden_field :user_id, value: current_user.id %>
<%= f.hidden_field :vote_type, value: 1 %>
<%= f.submit 'Upvote', class: 'btn btn-default' %>
<% end %>
<% end %>
My routes.rb
Rails.application.routes.draw do
get 'vote/create'
get 'vote/destroy'
get 'courses/new'
get 'users/new'
resources :courses do
resources :votes, only: [:create, :destroy, :update]
end
resources :users
end
I expect the param to pass 1 for vote_type, however, the actual output is nil
I am new to Rails. I am developing a web application where a user inserts inventory of shoes. So the user enters style code, size, price, and quantity. I want quantity to define how many entries there are in the database. So, if the quantity is three, three separate rows would be created for each shoe. Currently each form submission creates one row in the database.
My create in my shoe_controller:
def create
#shoe = Shoe.new(shoe_params)
respond_to do |format|
if #shoe.save
format.html { redirect_to #shoe, notice: 'Shoe was successfully created.' }
format.json { render :show, status: :created, location: #shoe }
else
format.html { render :new }
format.json { render json: #shoe.errors, status: :unprocessable_entity }
end
end
end
My _form.html.erb
<%= form_with(model: shoe, local: true) do |form| %>
<% if shoe.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(shoe.errors.count, "error") %> prohibited this shoe from being saved:</h2>
<ul>
<% shoe.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :sku %>
<%= form.text_field :sku %>
</div>
<div class="field">
<%= form.label :size %>
<%= form.text_field :size %>
</div>
<div class="field">
<%= form.label :quantity %>
<%= form.number_field :quantity %>
</div>
<div class="field">
<%= form.label :price %>
<%= form.text_field :price %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
What changes would I need to make to achieve the result I am looking for?
Thanks!
#rohit is correct in that using the Shoe.create method will get you what you want. But to implement this, you can change your controller to the following. I'm sure there are much cleaner ways of doing this, but it should get you what you're looking for. Also, I would suggest validating the quantity in shoe_params is a positive integer.
def create
#show = Show.new(shoe_params)
# This will create an array of shoes from your params
new_shoes = (1..shoe_params[:quantity]).collect { Shoe.new(shoe_params) }
# Save each record and put the result in an array
success = new_shoes.map(&:save)
if success.all?
# all records saved
else
# maybe #shoe.valid? is false or something else happened
end
end
you can use ActiveRecord::Persistence#create, which can accept an array of hashes as a parameter.
Suppose quantity is three, so build the 3 new hash which will contain your records.
shoes_params = [
{
code: 1,
size: 8,
price: 300,
quantity: 1
},
{
code: 1,
size: 8,
price: 300,
quantity: 1
}, ...
]
Shoe.create(shoes_params)
I'm trying to add a new player but it won't display and i keep getting a rollback. I've tried using hidden_field for my user_id but it didn't seem to do anything. Are there any other alternatives of doing this? I'm pretty sure its something so small that I have to change. Please help.
Player controller:
def new
#players = Player.new
end
def create
#players = Player.create(user_id: params[:player][:user_id], first_name: params[:player][:first_name], last_name: params[:player][:last_name], position: params[:player][:position], favorite_team: params[:player][:favorite_team], extra_equipment: params[:player][:extra_equipment], bio: params[:player][:bio])
redirect_to players_path
end
player new:
<h1>Add a new Player</h1>
<%= form_for #players do |f| %>
<p>First Name <%= f.text_field :first_name %></p>
<p>Last name <%= f.text_field :last_name %></p>
<p>Position <%= f.text_field :position %></p>
<p>Favorite Team(optional) <%= f.text_field :favorite_team %></p>
<p>Extra Equipment <%= f.text_field :extra_equipment %></p>
<p>Bio <%= f.text_field :bio %></p>
<%= f.hidden_field :user_id %>
<%= submit_tag "Add"%>
<% end %>
Player Model
class Player < ApplicationRecord
belongs_to :user
has_many :pickup, through: :player_pickup
end
For crud (Create, Update, Retrieve & Destroy) use #player, not #players.
Also, call your params from a private method instead calling it directly, this is a DRY concept in rails.
So it would be somehow like this (example):
def new
#player = Player.new
end
def create
#player = Player.new(player_params)
if #player.save
// Do something
else
// Do something
end
end
private
def player_params
params.require(:player).permit(:param_1, :param_2 .... etc)
end
Then in your view use form_for #player
You aren't passing a value into the hidden field. You should be doing something like
<%= f.hidden_field :user_id, value: current_user.id %>
If the user_id is always the current_user - you don't need a field, you can just assign it in the controller.
def create
#players = Player.create(first_name: params[:player][:first_name], last_name: params[:player][:last_name], position: params[:player][:position], favorite_team: params[:player][:favorite_team], extra_equipment: params[:player][:extra_equipment], bio: params[:player][:bio])
#players.user_id = current_user.id
#players.save
redirect_to players_path
end
Or - if you want to keep the same formatting
def create
#players = Player.create(user_id: current_user.id, first_name: params[:player][:first_name], last_name: params[:player][:last_name], position: params[:player][:position], favorite_team: params[:player][:favorite_team], extra_equipment: params[:player][:extra_equipment], bio: params[:player][:bio])
redirect_to players_path
end
Hi i want to send the selected object to a controller method but I dont know how. this is the select list with the vaules in it
Html------------
<%= form_tag '/wendy' do %>
<%= select_tag :'buenwendy', options_from_collection_for_select(#cursitos, 'id', 'name') %>
<%= submit_tag 'buscar', class: 'btn btn-success' %>
<% end %>
routes.rb
post 'wendy', to: 'blog#wendy
Controller------------------------------
def wendy
gg= params[:buenwendy]
flash[:success]= gg
redirect_to root_path
end
try this: after selecting course you will get can find that course at controller side and storing it in #gg variable
HTML...........
<%= form_tag( '/wendy', :method => :post ) %>
<%= select_tag :'buenwendy', options_from_collection_for_select(#cursitos, 'id', 'name') %>
<%= submit_tag 'buscar', class: 'btn btn-success' %>
<% end %>
......routes
post '/wendy', to: 'blog#wendy
controller..........
def wendy
#gg= Course.find(params[:buenwendy])
flash[:success]= #gg
redirect_to root_path
end
I solved it guys, I had to get the id of #cursitos from the SQL query
#cursitos = Course.find_by_sql("SELECT *courses.id*, courses.name FROM courses, cours_sts, students WHERE courses.id = cours_sts.course_id AND students.id = cours_sts.student_id AND students.id= 1")
I have a strange problem with my web app.
I am trying to build a simple reservation system for a game like "Escape the room". For now I made my own calendar looking a railscast (Calendars revised) for having the dates.
For the possible hours I made a new model and a new table in the database
t.integer "id"
t.datetime "start_time"
t.datetime "end_time"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
In the view I have something like this:
<%= calendar #date do |date| %>
<%= date.day %>
<table class="table">
<tbody>
<% #hours.each_slice(2) do |hour| %>
<tr>
<% hour.each do |h| %>
<td>
<%= link_to h.start_time.strftime('%H:%M'), new_escape_path(date: date, start_time: h.start_time.strftime('%H:%M'), end_time: h.end_time.strftime('%H:%M')) %>
</td>
<% end %>
</tr>
<% end %>
</tbody>
</table>
<% end %>
And I write these parameters into the database passing them in a form where user can complete other fields manually:
<%= text_field_tag :date, params[:date] %><br>
<%= text_field_tag :start_time, params[:start_time] %> do
<%= text_field_tag :end_time, params[:end_time] %>
The problem is that in the view I want to show only the hours which are not reserved yet, which means that they are not in the escapes table.
When in the console I write
Escape.all
I have something like:
#<Escape id: 1, date: "2015-08-11 00:00:00", start_time: "2015-08-10 08:30:00", end_time: nil, user_id: nil, created_at: "2015-08-10 15:26:14", updated_at: "2015-08-10 15:26:14">
but when I write
Escape.all.where(date: "2015-08-11 00:00:00")
it returns an empty record
#<ActiveRecord::Relation []>
I tried also to insert something like this in the view, but it's not working:
<% if Escape.where(["date = ? and start_time = ?", "#{date}", "#{h}"])%>
<%= h.start_time.strftime('%H:%M') %>
<% else %>
<%= link_to h.start_time.strftime('%H:%M'), new_escape_path(date: date, start_time: h.start_time.strftime('%H:%M'), end_time: h.end_time.strftime('%H:%M')) %>
<% end %>
Do you have any ideas? What am I doing wrong?