Is it a bad practice to create one of a CRUD action of one controller in another? For example we have two models User
,Post
and the following controller:
在另一个控制器中创建一个CRUD操作之一是不好的做法吗?例如,我们有两个型号User,Post和以下控制器:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
def update_post #update action of PostsController
Post.find(params[:post_id]).uppdate_attributes(params[:post])
end
def create_post #create action of PostsController
@user = User.find(params[:id])
@user.posts.create(params[:post])
end
end
Can/should I do like this or is there a better way ? The reason why this actions not in their own controller is that i want to manipulate posts at users page.
可以/我应该这样做还是有更好的方法?这个动作不在他们自己的控制器中的原因是我想操纵用户页面上的帖子。
1 个解决方案
#1
1
It is bad practice and impractical to do that if you have association already. You can use user
form and fields_for
to create/update `posts.
如果你已经有了联系,这是不好的做法,也是不切实际的。您可以使用用户表单和fields_for来创建/更新帖子。
You need to instantiate post with build
, add to user model accepts_nested_attributes_for
and use fields_for
in the view and user CRUD will save/update posts
您需要使用build实例化post,添加到用户模型accepts_nested_attributes_for并在视图中使用fields_for,用户CRUD将保存/更新帖子
#user controller
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@user.posts.build
end
end
#user model
accepts_nested_attributes_for :posts
#user/show view
<%= form_for @user do |f| %>
<%= f.fields_for :posts do |post| %>
<%= post.text_field :post %>
<% end %>
<% end %>
#1
1
It is bad practice and impractical to do that if you have association already. You can use user
form and fields_for
to create/update `posts.
如果你已经有了联系,这是不好的做法,也是不切实际的。您可以使用用户表单和fields_for来创建/更新帖子。
You need to instantiate post with build
, add to user model accepts_nested_attributes_for
and use fields_for
in the view and user CRUD will save/update posts
您需要使用build实例化post,添加到用户模型accepts_nested_attributes_for并在视图中使用fields_for,用户CRUD将保存/更新帖子
#user controller
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@user.posts.build
end
end
#user model
accepts_nested_attributes_for :posts
#user/show view
<%= form_for @user do |f| %>
<%= f.fields_for :posts do |post| %>
<%= post.text_field :post %>
<% end %>
<% end %>