表格下拉选择关系

时间:2011-01-15 18:36:30

标签: ruby-on-rails ruby-on-rails-3

我对此感到困惑。我有一个公司模型和一个消息模型。公司has_many消息和消息belongs_to公司。我将数据保存到正确的公司时出现问题,此表格已保存。

<%= form_for(@msg) do |f| %>
  <%= render 'errors', :object => f.object %>
    <ul class="fields">
      <li> 
        <%= select("msg", "company_id", Company.all.collect {|p| [ p.title, p.id ] }) %>
      </li>
    </ul>
    <ul class="fields">
      <li><%= f.label :content, "Send this company your message" %></li>
      <li><%= f.text_area :content %></li>
    </ul>
    <div id="actions">
      <%= f.submit "Send" %>
    </div>
<% end %>

每次保存此表单时,company_id为null。我要保存的控制器的代码是

def create
  @msg = current_user.messages.build(params[:msg])
  if @msg.save
    flash[:success] = "New message saved"
    redirect_to current_user
  else
    render current_user
  end
end

对于我为什么不保存这一点没有什么特别突出的,有人能引导我走向正确的方向吗?

杰夫

1 个答案:

答案 0 :(得分:0)

在您的控制器中,您不需要找到当前的公司吗?像

这样的东西
@company = Company.find(params[:company_id])
@message = @Company.messages.create(params[:msg]) 

会奏效。至于混合has_many与用户和公司,SO上的这个线程似乎很好。 Rails Model has_many with multiple foreign_keys