开发者

Rails, Model Relationship Question

I have the following which works great:

@request_thread 开发者_如何学编程= current_user.request_threads.new(params[:request_thread])

And I have this which works great:

@requestable = find_requestable
@request_thread = @requestable.request_threads.new(params[:request_thread])

But if I try the 2nd line with:

@request_thread = @requestable.current_user.request_threads.new(params[:request_thread])

With the current_user I get the following error:

NoMethodError (undefined method `current_user' for #<Photo:0x10f95c828>):
app/controllers/request_threads_controller.rb:52:in `create'
app/middleware/flash_session_cookie_middleware.rb:14:in `call'

What did I mess up on here?

Thanks

UPDATE - with find_requestable

  # http://asciicasts.com/episodes/154-polymorphic-association
  def find_requestable  
    params.each do |name, value|  
      if name =~ /(.+)_id$/  
        return $1.classify.constantize.find(value)  
      end  
    end  
    nil  
  end


The error message tells you exactly whats wrong: current_user doesn't exist for the @requestable object, whatever that is.

current_user is most likely a function inherited from ApplicationController, or at least that's usually where it lives. It usually returns a User object according to the current session. But that isn't a built-in part of Rails, so we need more information if you want me to go into greater detail.

@requestable looks like a polymorphic model instance so it wouldn't be aware of the current session.


There's a bit of Rails magic happening here that I think is confusing you.

Both @requestable.request_threads and current_user.request_threads are helper functions that have been generated by Rails on those objects to save you time by filtering results and filling in values automatically.

I think, by the code you have shown us so far, that you are trying to associate current_user with the new request_thread you are creating. In that case, you can simple merge that into the attributes manually. Since I don't know what your models look like I can only guess at the field names:

@request_thread = @requestable.request_threads.new( params[:request_thread].merge(:user => current_user) )

Like I said, the chainable functions are merely for convenience. For instance, you could write it this way instead:

@request_thread = request_thread.new(params[:request_thread])
@request_thread.requestable = find_requestable
@request_thread.user = current_user
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜