0

我试图将这些模型关联到创建栏的动作。协会!为什么那么无?

我知道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> 
+0

顺便说一句,你可能不想使用“type”作为模型名称。参见例如http://juicebar.wordpress.com/2007/05/30/reserved-words-in-rails/ – 2012-03-10 22:39:24

+0

woow!我从来没有想过这个,铁轨充满了隐藏的技巧! – dcalixto 2012-03-10 23:02:19

回答

1

尝试构建bar对象是这样的:

@bar = current_user.bar.new params[:bar].merge(:type_id => @type.id) 

确保您同时拥有current_user对象和@type当你打电话给这条线的时候。

为了记录在案,current_user.bar.newcurrent_user.bar.build之间的唯一区别是,build添加新创建bar对象到用户的收集保存它(其中为new不会将对象添加到用户,直到它实际上保存)前。

+0

感谢帮助的人!但零点疯狂仍然活着 – dcalixto 2012-03-10 22:59:24

+0

将您的调用更改为'@ bar.save!'(带有感叹号),然后在您的原始文章中追加输出到日志中的错误(可能在'log/development.log'中。需要知道它正在寻找哪个'id' – 2012-03-10 23:17:36

+0

here去吧!开始POST“/ bars”为127.0.0.1于2012-03-10 20:28:37 -0300 BarsController处理#create as HTML 参数:{ “utf8”=>“✓”,“authenticity_token”=>“fLI8ffLhMXWklCy7CMZWBxIvqfbBKi6Al5vo269FyYM =”,“bar”=> {“name”=>“sssss”,“type”=> {“style”=>“Pub”}} ,“提交”=>“创建”} 1 2 3 4 5 6 7 8 9 10 [0m [35m用户负载(0.2ms)[0m SELECT“users”。* FROM“users”WHERE“users”。“auth_token”='pwXhuBLyjau1OEdaTxKuvw'LIMIT 1 [ 36mBar负载(13.5ms)[0m [1mSELECT“bars”。* FROM“bars”WHERE“bars”)。“user_id”= 11 LIMIT 1 [0m – dcalixto 2012-03-10 23:36:27

相关问题