[英]Rails - Creating a record in a join model but with an attribute
I have a Join Model I just Migrated called EventUsers that has an user_id, event_id, and an attribute i created called opinion:string 我有一个刚刚迁移的Join模型,称为EventUsers,它具有一个user_id,event_id和一个我创建的属性,称为Opinion:string
create_table :events_users, :id => false do |t|
t.integer :user_id
t.integer :event_id
t.string :opinion # extra attribute I made
end
and event.rb 和event.rb
has_and_belongs_to_many :users
and user.rb 和user.rb
has_and_belongs_to_many :events
I can add to the join model with 我可以添加到加入模型
@user = User.find(session[:user_id])
@event = Event.find(params[:id])
@user.events << @event
but before I do that...... How do I set the opinion attribute to some string and then insert? 但是在执行此操作之前……如何将Opinion属性设置为某个字符串,然后插入?
If your join model has any fields other than just the foreign keys, then you shouldn't be using a HABTM relationship. 如果您的联接模型除了外键之外还具有其他字段,那么您不应该使用HABTM关系。 You should create an intermediate model such as Opinion and have each model related like so:
您应该创建一个中间模型(例如Opinion),并使每个模型相互关联,如下所示:
class Event < ActiveRecord::Base
has_many :opinions
has_many :users, :through => :opinions
end
class User < ActiveRecord::Base
has_many :opinions
has_many :events, :through => :opinions
end
class Opinion < ActiveRecord::Base
belongs_to :user
belongs_to :event
end
Update: 更新:
In order to add opinions, you will likely want to create a RESTful interface. 为了添加意见,您可能需要创建一个RESTful接口。 I would start by adding a nested route within either users, events, or both
我将从在用户,事件或两者中添加嵌套路由开始
map.resources :users do |user|
user.resources :opinions
end
Then add an opinions controller with your standard RESTful actions (new, create, edit, update, etc) and corresponding views. 然后添加带有标准RESTful操作(新的,创建,编辑,更新等)和相应视图的意见控制器。 There are tons of resources on how to build a standard restful interface, but I would start with these:
关于如何构建标准的Restful接口,有大量资源,但我将从以下内容开始:
http://guides.rubyonrails.org/routing.html#resource-routing-the-rails-default http://guides.rubyonrails.org/routing.html#resource-routing-the-rails-default
http://guides.rubyonrails.org/routing.html#nested-resources http://guides.rubyonrails.org/routing.html#nested-resources
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.