ruby on rails - CRUD action of one controller in another -
is bad practice create 1 of crud action of 1 controller in another? example have 2 models user
,post
, following controller:
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 or there better way ? reason why actions not in own controller want manipulate posts @ users page.
it bad practice , impractical if have association already. can use user
form , fields_for
create/update `posts.
you need instantiate post build
, add user model accepts_nested_attributes_for
, use fields_for
in view , user crud save/update posts
#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 |f| %> <%= f.fields_for :posts |post| %> <%= post.text_field :post %> <% end %> <% end %>
Comments
Post a Comment