我试图将这些模型关联到创建栏的动作。协会!为什么那么无?
我知道bar和type都是nil没有创建的对象,但为什么ruby不明白我想要的只是绑定这些nil对象?
所以,我搜索的答案,但他们没有解释清楚为什么这个错误:的零名为id,这将被错误地4 - 如果你真的想零的ID,请使用OBJECT_ID
发生在这种情况下。
用户 - 型号
has_one :bar
酒吧 - 型号
belongs_to :type
belongs_to :user
类型 - 型号
has_many :bars
酒吧 - 控制器
def new
@bar = Bar.new
end
def create
@bar = current_user.build_bar(params[:bar].merge(:type_id => @type.id))
if @bar.save
flash.now[:success] = "Wohoo!"
redirect_to @bar
else
render :new
end
end
New_bar - 查看
<div class="block">
<%= render 'shared/flash_messages' %>
<%= form_for @bar, :url => bars_path, :method => :post do |b| %>
<ul>
<li><%= b.label :name %><%= b.text_field :name %></li>
<%= b.fields_for :type do |t| %>
<li>pirate:<%= t.radio_button :style, "pirate" %></li>
<li>pub:<%= t.radio_button :style, "pub" %></li>
<li>american:<%= t.radio_button :style, "american" %></li>
</ul>
<% end %>
<%= b.submit "create", :class => "sec button" %>
<% end %>
</div>
顺便说一句,你可能不想使用“type”作为模型名称。参见例如http://juicebar.wordpress.com/2007/05/30/reserved-words-in-rails/ – 2012-03-10 22:39:24
woow!我从来没有想过这个,铁轨充满了隐藏的技巧! – dcalixto 2012-03-10 23:02:19