Rails 4 如何编辑来自不同模型的对象?

Rails 4 How to edit an object from a different model?

如何从模型 B 视图编辑模型 A 中的对象?模型是关联的。我已经尝试对 object_id ( link_to 'Edit' edit_a_path(2) ) 进行硬编码并且它当然有效。但是我怎样才能动态地做到这一点?

如果模型 A 是 User,模型 b 是 Post 并且用户 has_many 发帖,那么您将能够像这样访问用户发帖:

# In controller
@user = User.find(params[:id])

# In view

# if user has_many posts
<% @user.posts.each do |post| %>
  <%= link_to 'Edit', edit_post_path(post) %>
<% end %>

# if user has_one post
<%= link_to 'Edit', edit_post_path(@user.post) %>

虽然这可能无法反映您的模型,但如果没有,请发表评论。

你应该看看 the rails association guide or for a more in depth understanding do the rails tutorial by Michael Hartl。厉害了。