Jshoe523
Jshoe523

Reputation: 4181

Rails create action with multiple belongs_to

Trying to figure out a better way of assigning a review it's associated models.

I have the following classes:

class User < ActiveRecord::Base
  has_many :reviews, dependent: :destroy
end

class Review < ActiveRecord::Base
  belongs_to :user
  belongs_to :restaurant
end

class Restaurant < ActiveRecord::Base
    has_many :reviews, dependent: :destroy
end

Pretty straightforward stuff. A review must have a restaurant and a user. My create action looks like this:

def create
    @restaurant = Restaurant.find(params[:restaurant_id])
    @review = @restaurant.reviews.build(review_params)
    @review.user = current_user

    if @review.save
        redirect_to @restaurant
    else
        render 'new'
    end
  end

  private
  def review_params
    params.require(:review).permit(:content)
  end

Currently I build the review for the restaurant and then I assign the review's user to the current user.

This all works fine but is there a cleaner way to build the associations? Is there a way to add additional arguments to the build method alongside the strong params?

I looked at accepts_nested_attributes_for but I couldn't get it to work.

Thanks!

Upvotes: 2

Views: 355

Answers (2)

Pavan
Pavan

Reputation: 33542

You can use merge in the review_params like below

def review_params
  params.require(:review).permit(:content).merge(user_id: current_user.id)
end

so that you can erase this line @review.user = current_user in the create method

Upvotes: 2

Ryan K
Ryan K

Reputation: 4053

In your form, you can put a hidden field with the user_id that you want to assign:

<%= f.hidden_field :user_id, value: @user.id %>

Then, add it to your review_params:

params.require(:review).permit(:content, :user_id)

Upvotes: -1

Related Questions