I want to return a single result using .find() with Ruby on Rails

后端 未结 3 1261
予麋鹿
予麋鹿 2021-01-21 14:19

I have a user view and a rental view. In my rental view im trying to show the current users name. I think I am pretty close but I can\'t work out this last bit.

This ret

相关标签:
3条回答
  • 2021-01-21 14:44

    I think you should be able to do:

    <%= f.select :user_id, User.find(f.object.user_id).collect {|t| [t.user_name, t.id]} %>
    

    This does seem a little odd to me though. I'd have thought either:

    • Your object has a proper association to the relevant user, in which case you should be able to do f.object.user.user_name and f.object.user.id.
    • If you genuinely want the currently logged in user, you should probably be asking your authentication framework/code for the reference. E.g. if you were using Devise, it would be current_user.

    As an aside, I don't really understand why you want a select list just containing the current user - is that definitely what you're trying to achieve, or have I misunderstood?

    0 讨论(0)
  • 2021-01-21 14:57

    find() wants a variable, not a symbol. And :all probably isn't what you want. You should write a method in your controller like:

    def user(u)
      @user = User.find(u)
    end
    

    Then call the method in the view or whatever like (I don't know exactly what you're trying to do here):

    <% user(current_user.id) %>
    

    Then you'll have a @user object with which you may play, i.e.:

    <%= f.select :user_id, [[@user.name, @user.id]] %>
    
    0 讨论(0)
  • 2021-01-21 15:02

    I am assuming you have a rental object, for which you show the form, I assume it is an instance variable @rental, furthermore I assume that inside your Rental class there is the following relation

    class Rental
    
      belongs_to :user
    
    end
    

    Then you could just write the following:

    f.select :user_id, [[@rental.user.user_name, @rental.user.id]]
    

    Hope this helps.

    On a related but less important note: it is really weird to have a column called user_name for a user: I would call that column just name, since it is part of a user anyway.

    0 讨论(0)
提交回复
热议问题