form drop down select relationship

安稳与你 提交于 2019-12-24 22:25:34

问题


I am confused with this. I have a company model and a message model. Company has_many messages and messages belongs_to company. I am having problems with the data being saved to the proper company with this form is saved.

<%= 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 %>

every time this form is saved the company_id is null. My code for the controller to save is

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

Nothing stands out to me as to why this is not saving, can someone guide me to the right direction?

Jeff


回答1:


In your controller, don't you need to find the current company? Something like

@company = Company.find(params[:company_id])
@message = @Company.messages.create(params[:msg]) 

would work. As far as mixing has_many with both users and companies, this thread on SO seems good. Rails Model has_many with multiple foreign_keys



来源:https://stackoverflow.com/questions/4701413/form-drop-down-select-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!