开发者

Rails MVC: Should a form collection_select know which collection records it should render?

开发者 https://www.devze.com 2023-03-15 21:08 出处:网络
I\'m a little stuck here with a conceptual issue. Assume following [abstracted] setup for Post, Tag, and User:

I'm a little stuck here with a conceptual issue. Assume following [abstracted] setup for Post, Tag, and User:

Post  belongs_to Tag
Tag   has_many   Posts
User  has_many   Tags,
      has_many   Posts

A user can only tag a post with one of his associated tags.

In the new post form view, I now have following options for selecting a tag:

  1. f.collection_select :tag_id, current_user.tags, ...

  2. f.collection_select :tag_id, @tags, and in the controller's new action:

    @tags = current_user.tags

Question: What is the conceptually correct option?

From an MVC perspective, I definitely tend towards using the second option. It does not seem right that 开发者_如何学Gothe view knows that the tags it should render in the collection_select are associated to a user (even more specific, the current user!).

However, in the official api documentation for collection_select and some other tutorials around the web I see something like this:

collection_select(:post, :author_id, Author.all, ...)

which clearly favors the first option. On the pro-site of this approach, I do not need to redefine the @tags in the create action of the controller in case the post's save action fails and I want to render the new action again.

Thank you for your suggestions in advance.


There's nothing wrong with your first option. For starters, it's simpler (one less line of code). Setting an extra instance variable within your controller doesn't really gain you anything.

A good way of thinking about the controller is that it should only be doing things like setting variables when they are based directly upon input that only the controller receives (such as parameters in the URL, query string, or data from a POSTed form).

The view in this case isn't deciding how to determine the current user - that's still coming from your controller (although probably inherited from the top-level ApplicationController or something like Devise?), all it's doing is deciding that it's the tags of the current user which should be be selectable within the drop-down view.

Does that help?

0

精彩评论

暂无评论...
验证码 换一张
取 消