简体   繁体   English

用于部分HABTM关联的Select语句

[英]Select statement in a form partial for an HABTM association

I have two models Client and Topic . 我有两个模型ClientTopic Both of which have a HABTM association between them. 两者之间都具有HABTM关联。

I am trying to add a select statement in my _form partial in my Client views, that allows the user to add a topic to a client (or edit that topic, etc.). 我正在尝试在Client视图的_form部分中添加一条select语句,该语句允许用户向客户端添加主题(或编辑该主题,等等)。

This is what my form partial looks like: 这是我的表单部分的样子:

<%= form_for(@client) do |f| %>

  <div class="field">
    <%= f.label :topic %><br />
    <%= f.select :topics, Topic.all.collect { |topic| [topic.name, topic.id] }, {:include_blank => 'None'} %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

The first error I got was this: 我得到的第一个错误是:

ActiveModel::MassAssignmentSecurity::Error in ClientsController#create

Can't mass-assign protected attributes: topics

So, in my Client model, I added this: 因此,在我的Client模型中,我添加了以下内容:

attr_accessible :email, :firm_id, :name, :phone, :topics

This is the error I now get: 这是我现在得到的错误:

NoMethodError in ClientsController#create

undefined method `each' for "1":String

The create action of my Clients controller is very standard: 我的Clients控制器的创建动作非常标准:

  def create
    @client = Client.new(params[:client])

    respond_to do |format|
      if @client.save
        format.html { redirect_to @client, notice: 'Client was successfully created.' }
        format.json { render json: @client, status: :created, location: @client }
      else
        format.html { render action: "new" }
        format.json { render json: @client.errors, status: :unprocessable_entity }
      end
    end
  end

These are the params submitted (notice that topics is being passed - instead of topic_id but topic_id doesn't work either): 这些是提交的参数(请注意,正在传递topics -代替topic_idtopic_id也不起作用):

{"utf8"=>"✓",
 "authenticity_token"=>"J172LuZQc5NYoiMSzDD3oY9vGmxxCX0OdxcGm4GSPv8=",
 "client"=>{"name"=>"Jack Daniels",
 "email"=>"jack.daniels@some-email.com",
 "phone"=>"2345540098",
 "firm_id"=>"2",
 "topics"=>"1"},
 "commit"=>"Create Client"}

How can I get a topic assigned to my client on the creation of the client with this select statement? 在使用此select语句创建客户端时,如何获得分配给客户端的主题?

Thanks! 谢谢!

When setting a "Topic" attribute, Client expects an instance of a Topic class. 设置“主题”属性时,客户端需要主题类的实例。

Since you are passing IDs, you need to change: 由于您要传递ID,因此需要更改:

<%= f.select :topics, Topic.all.collect { |topic| [topic.name, topic.id] }, {:include_blank => 'None'} %>

to set topic_ids instead: 改为设置topic_ids

<%= f.select :topic_ids, Topic.all.collect { |topic| [topic.name, topic.id] }, {:include_blank => 'None'} %>

And, of course, in attr_accessible: 并且,当然,在attr_accessible中:

attr_accessible :email, :firm_id, :name, :phone, :topic_ids

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM