Rails - how to show attribute of an associated model

后端 未结 2 755
臣服心动
臣服心动 2020-12-22 00:58

I am trying to make an app in Rails 4.

I just asked this related question and got a clear answer. It seems I can\'t understand how to take that logic and apply it e

2条回答
  •  粉色の甜心
    2020-12-22 01:46

    I think that you need to understand some basic concepts of Ruby and Ruby and Rails to solve this question yourself.

    In ruby, vars with @ are instance variables and are available all over the class. That means that they will be available in your view if you declare them in your controller.

    EG @creator_profile = @profile.user

    On the other hand, vars without @ are only available inside the same block.

    An example:

    #controller
    @users = User.all #@users, instance variable
    
    #view
    <% @users.each do |user| %>
      

    <%= user.name %>

    #user, local variable. This will work <% end %>

    <%= user.name %>

    #this won't work because it is outside the block

    Google about ruby vars and scopes.

    Also, I think that you are relying too much on 'rails magic' (or you are skipping some code lines), if you don't declare an instance var, it won't exist. Naming conventions don't work that way.

    At last but not at least, having a look at your relations, I think that they need some refactor. Also the use of singular and plural is not correct. I know that it's not real code but it denotes that they don't reflect real relationships between entities.

    Don't try to make 'octopus' models, where everybody belongs to everybody, and think about the relationships itself, not only trying to associate models. EG:

    Profile
    belongs_to :creator, class_name: 'User'
    

    This way you can write:

    #controller
    @profile_creator = Profile.find(params[:id]).creator
    
    #view
    @profile_creator.university
    

    You will understand better what you are doing.

    Hope it helps.

提交回复
热议问题