My models:
brand.rb
has_many :products
has_many :votes
belongs_to :user
accepts_nested_attributes_for :products, :allow_destroy => true
product.rb
belongs_to :user
belongs_to :brand
vote.rb
belongs_to :brand
belongs_to :user
routes.rb
resources :brands do
resources :products
end
My goal: Create 2 records (product and vote) on existing Brand record in 1 form, on brand/show
page.
My solution:
brand/show.html.erb
<% form_for([@brand, @brand.send(:product).klass.new]) do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :price %>
<%= f.text_field :price %>
<%= fields_for :votes, @brand.votes.new do |builder| %>
<%= builder.label :rating %>
<%= builder.text_field :rating %>
<% end %>
<%= f.submit %>
<% end %>
products_controller.rb
def create
if Brand.exists?(:id => params[:brand_id])
@review = Review.new(review_params)
@vote = Vote.new(votes_params)
@review.user_id = @vote.user_id = current_user.id
@review.brand_id = @vote.brands_id = params[:brand_id]
if @vote.valid? && @review.valid?
@vote.save
@review.save
redirect_to brands_path
else
flash[:errors][:vote] = @vote.errors
flash[:errors][:review] = @review.errors
redirect_to brands_path
end
end
end
private
def product_params
params.require(:review).permit(:title, :price)
end
def votes_params
params.require(:votes).permit(:rating)
end
Is this right way of solving my task? Can I use it like that?
This is how I would refactor your create method:
Also, little improvements:
You will obviously have to update your strong params accordingly, but this is the easy part ;-)