开发者

How to include an id in the nested form?

开发者 https://www.devze.com 2023-04-12 18:12 出处:网络
I have a nested form ,and i want to include city_id in the stores model,is this <%= s.hidden_field :city_id, @city.id %> correct? If yes what do i add in the controller after that? If it is not

I have a nested form ,and i want to include city_id in the stores model,is this <%= s.hidden_field :city_id, @city.id %> correct? If yes what do i add in the controller after that? If it is not a correct way to include it can anybody show me the right way please? Much thanks.

<%= form_for @deal ,:url=>{:action =>"create"} do |c|%>
  <%= c.text_field :item_name %>
  <%= c.text_field :price %>

  <%=c.fields_for :stores do |s| %>
    <%=s.text_field :store_name %>
    <%= s.hidden_field :city_id, @city.开发者_高级运维id %>
    <%=s.text_field :address %>
  <%end%>           

  <%= c.submit "post"%>     
<%end%>

controller

def create
  @city = City.find(session[:city_id])
  @deal=@city.deals.build(params[:deal])

  if @deal.save
    redirect_to @deal
    flash[:notice]="successfully created"
  else
    render 'new' 
  end 
end

models

class City < ActiveRecord::Base
    has_many :stores
    has_many :deals 
end

class Deal < ActiveRecord::Base
    belongs_to :city
    has_many :stores ,:through =>:store_deals
    has_many :store_deals
end

class StoreDeal < ActiveRecord::Base
    belongs_to :store
    belongs_to :deal
end

error

NoMethodError in Deal#new

Showing /home/Deals/app/views/deal/new.html.erb where line #13 raised:

undefined method `merge' for 2:Fixnum
Extracted source (around line #13):

10: <tr><td><label>Price</label></td><td><%= c.text_field :price %></td></tr>
11: <%=c.fields_for :stores do |s| %>
12: <tr><td><label>Store</label></td><td><%=s.text_field :store_name %></td></tr>
13: <%= s.hidden_field :city_id, @city.id %>
14: <tr><td><label>Cross street</label></td><td><%=s.text_field :address %></td></tr>
15: <%end%>
16: <tr><td><%= c.submit "post"%></td></tr>


Okay, now that I've looked over your code more carefully and seen the it's clear what the problem is. The hidden_field helper doesn't have value as one of its arguments. Use:

<%= s.hidden_field :city_id, :value => @city.id %>

However, for the reason Michael Durrant points out, it would be better to handle this in your controller.

0

精彩评论

暂无评论...
验证码 换一张
取 消