【问题标题】:Rails HABTM Relation with multiple form elementsRails HABTM 与多个表单元素的关系
【发布时间】:2012-11-27 00:24:05
【问题描述】:

我正在做一个需要 has_and_belongs_to_many 关系的项目。

这涉及拥有许多“提案”的用户和属于许多用户的提案。

这很重要,因为用户可以创建提案并邀请其他用户参与。

我无法正确设置,已阅读许多其他教程和 SO 问题,但无法对其进行排序。

这是我目前所拥有的。

User.rb

class User < ActiveRecord::Base
  has_and_belongs_to_many :proposals
 .......


Proposal.rb

class Proposal < ActiveRecord::Base
  has_and_belongs_to_many :users
...


database migration for HABTM

class CreateProposalUserJoinTable < ActiveRecord::Migration
  def change

  create_table :proposals_users, :id => false do |t|
    t.integer :user_id
    t.integer :proposal_id
  end
  end
end


/views/proposals/_form.html.erb
...
<%= f.collection_select(:users, User.all, :id, :trading_name) %>

<%= f.collection_select(:users, User.all, :id, :trading_name) %>

<%= f.collection_select(:users, User.all, :id, :trading_name) %>

...

这是我希望用户选择三个用户并将他们添加到关系中的地方。

我已尝试将此逻辑添加到控制器,但无法使其正常工作。

最初我将它与 id 作为外键一起破解,但想使用活动记录关联。

[编辑]

proposals_controller.rb
 def create
    @proposal = Proposal.new(params[:proposal])

    if current_user
     @user = current_user

     @proposal.creator_id = @user.id
     @proposal.cost = 10


    end

    respond_to do |format|
      if @proposal.save


       (params[:proposal][:users]).each do |user|
          if user.to_i.to_s == user || user.to_f.to_s == user
            puts user 
            puts "********************\n\n\n\n\n\n\n"
            @proposal.users = User.find(user)

         User.find(user).proposals << @proposal
        end
        end
        @proposal.save
        format.html { redirect_to @proposal, notice: 'proposal was successfully created.' }
        format.json { render json: @proposal, status: :created, location: @proposal }
      else
        format.html { render action: "new" }
        format.json { render json: @proposal.errors, status: :unprocessable_entity }
      end
    end

  end

【问题讨论】:

  • 最终这在控制台中工作得很好,但我的 collection_select 有问题。我需要它来返回用户,而不是用户的 id...在它崩溃时的参数中,当我需要用户模型时,它有 users => 1,(对于用户 id 1)。
  • 但是,即使我添加了一个隐藏字段来将用户的值分配给用户(id ==1),它也会引发此错误:未定义的方法 `each' for "#<0xb1be260>

标签: ruby-on-rails ruby relationship has-and-belongs-to-many


【解决方案1】:

不必将用户分配给提案。相反,您也可以分配 id,如下所示:

proposal.user_ids = params[:proposal][:user_ids]

在下面的代码中,赋值是自动完成的:

proposal.attributes = params[:proposal]

要完成这项工作,应该像这样更改视图:

<%= select_tag("proposal[user_ids][]", options_from_collection_for_select(User.all, :id, :trading_name)) %>

【讨论】:

  • 我得到这个响应改变如上:'NoMethodError in ProposalsController#create undefined method `proposals' for #<0xbde8eb4>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-21
  • 2011-07-12
  • 1970-01-01
  • 1970-01-01
  • 2014-03-12
  • 1970-01-01
相关资源
最近更新 更多