[英]How to create data entry with association in rails?
Now I have models of users and their articles. 现在,我有了用户及其文章的模型。 However, how do I implement the articles controller so that it keeps track of which user is the author?
但是,如何实现Articles控制器,以便跟踪作者是哪个用户? Should I pass a parameter back or is there any API to use?
我应该传回参数还是要使用任何API?
In article model , 在文章模型中,
belongs_to :user
and in user model, 在用户模型中
has_many :articles
Now , you have one to many relation , from user to article . 现在,您从用户到文章都有一对多的关系。 Just add an attribute author in user table.
只需在用户表中添加属性作者。 This is how u can apply the logic
这就是你可以运用逻辑的方式
in app/models/article.rb
belongs_to :user
in app/models/user.rb
has_many :articles
and in controller(new action) you will write
在控制器(新动作)中,您将编写
current_user.articles.new
current_user.articles.new
or
要么
current_user.articles.build
current_user.articles.build
and in controller(create action) you will write
在控制器(创建动作)中,您将编写
current_user.articles.create(params[:article])
current_user.articles.create(params [:article])
or
要么
article = current_user.articles.build
article = current_user.articles.build
article.attributes = params[:article]
article.attributes = params [:文章]
and if you want to fetch only user's articles then you will do in edit action
如果您只想获取用户的文章,则可以执行编辑操作
current_user.articles.find(params[:id]), where params[:id] is article id which is to be edited.
current_user.articles.find(params [:id]),其中params [:id]是要编辑的商品ID。
and in controller(update action) you will write
在控制器(更新操作)中,您将编写
article = current_user.articles.find(params[:id])
article = current_user.articles.find(params [:id])
article.update_attributes(params[:article])
article.update_attributes(params [:article])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.