Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/EmptyTag/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails-使用属性(HABTM+;至)连接表,但如何创建/删除记录?_Ruby On Rails_Syntax_Has Many Through - Fatal编程技术网

Ruby on rails Rails-使用属性(HABTM+;至)连接表,但如何创建/删除记录?

Ruby on rails Rails-使用属性(HABTM+;至)连接表,但如何创建/删除记录?,ruby-on-rails,syntax,has-many-through,Ruby On Rails,Syntax,Has Many Through,我有一个用户模型和兴趣模型,由一个名为Choice的联接表联接(详情如下)。我使用HABTM与through的关系,因为我在join表中也有一个属性 User.rb has_many :choices has_many :interests, :through => :choices 利息.rb has_many :choices has_many :users, :through => :choices Choice.rb belongs_to :user belongs_to

我有一个用户模型和兴趣模型,由一个名为Choice的联接表联接(详情如下)。我使用HABTM与through的关系,因为我在join表中也有一个属性

User.rb

has_many :choices
has_many :interests, :through => :choices
利息.rb

has_many :choices
has_many :users, :through => :choices
Choice.rb

belongs_to :user
belongs_to :interest
所以问题是如何将记录添加到这个新创建的选项表中。例如=>

@user = User.find(1)
@interest = Interest.find(1)
?????   Choice << user.id + interest.id + 4(score attribute) ??????
@user=user.find(1)
@兴趣=兴趣。查找(1)

????? Choice您有几个选项可以添加选项,但最有意义的可能是通过对用户实例的作用域来添加选项:

假设:

@user = User.find(1)
@interest = Interest.find(1)
您可以添加如下选项:

@user.choices.create(:interest => @interest, :score => 4)
您也可以在控制器中执行以下操作:

def create
  @choice = @user.choices.build(params[:choice])

  if @choice.save
    # saved
  else
    # not saved
  end
end

<强>此假设您的表单具有“代码< >选择字段[:兴趣ID ] /代码>和<代码>选择[(得分)< /代码> <强> > /p>,无论如何都要检查是否已添加了记录并更新,如果是这样的话,可能是,但您可能需要考虑提供一个用于管理选择的REST接口。每个选项都有一个编辑/更新UI,用户可以在其中单独管理每个选项。一旦你搞定了这个,你就可以为一个编辑到位类型的界面添加一些JS。