views:

34

answers:

1

Hi,

I have an object called Review which :belongs_to two objects: Users and Vendors. In other words, there is always a vendor writing a review for a specific vendor.

When I create a review, I tried to use the .build method to presumably add the foreign_key at the time the new record is created for review.vendor_id and review.user_id.

When I put into the controller for review the build statement for user id without one for capturing the vendor id, it works like a charm. When I add the vendor_id the user_id stays 'nil'.

Help? Reviews is a nested resource: vendors/3/reviews/new

Forms for review/new:

<% form_for [@vendor, @review] do |f| %>

In the review controller:

    def new
      @vendor = Vendor.find(params[:vendor_id])
      @review = @vendor.reviews.build
      #@review = Review.new
    end



def create
    @vendor = Vendor.find(params[:vendor_id])
    @review = @current_analyst.reviews.build params[:review]

    if @review.save
      flash[:notice] = "Successfully created review."
      redirect_to review_path(@review)
    else
  render :action => 'new'
end

end

+1  A: 

This is your problem.

@review = @current_analyst.reviews.build 
@vendor = Vendor.find(params[:vendor_id])  
@review = @vendor.reviews.build params[:review]

You are overwriting @review with a new Review generated by @vendor.reviews.build. Instead of creating a new Review, you should just set the second foreign key using the methods created by the belongs_to association. Like this:

@review = @current_analyst.reviews.build params[:review]
@review.vendor_id = params[:vendor_id]

To speed this process up, you can make :vendor_id part of the form_for @review. Assuming a Review is a nested resource of Vendor

Example:

Controller Actions:

def new 
  @vendor = Vendor.find(params[:vendor_id])
  @review = @vendor.reviews.build
end

def create
  @review = @current_analyst.reviews.build params[:review]
  if @review.save
    redirect_to @review
  else
    render :action => :new
  end
end

Form partial:

<% form_for @review do |f| %>
  ...
    Standard form information
  ...
  <%= f.hidden_field :vendor_id%>
  <%= submit_tag %>
<% end %>
EmFi
Is there a way I could not use the hidden field? Yes, it is a nested resource vendor/3/reviews/new....is it possible to do form_for [@vendor,@review] and get rid of the hidden field? That would be perfect!
Angela