开发者

Ruby on Rails: passing parameters from other controllers to a model

开发者 https://www.devze.com 2022-12-18 17:15 出处:网络
I have in a users_controller: @user = User.new(params[:user]) Passing parameters to a User model which works fine.

I have in a users_controller:

@user = User.new(params[:user])

Passing parameters to a User model which works fine.

I need to pass some additi开发者_如何学Pythononal parameters labeled "profile" to the user model through the users controller.

This didn't work:

    @user = User.new(params[:user, :profile])

Neither did this:

    @user = User.new(params[:user], params[:profile])

I tried a variety of other similar things to get the profile parameters from the view into this model.

I'm using fields_for which works fine to get these fields into the users controller:

  <% fields_for "profile" do |fa| %>

I don't need/want a nested relationship. I just need to simply pass some additional parameters specified in the view to the model.

Thanks!


fields_for is generally used for assigning params to a related model, so it makes some particular assumptions about the structure of the data.

If you have a profile attribute in your model, you can make the profile parameter part of the params[:user] collection and this will assign the attribute correctly.

You do this by naming the fields:

text_field_tag(user[profile], "val") 

text_field_tag(user[profile][name], "val") 


Thanks Toby!

Just to add to his answer. I had to put

attr_accessor :profile

in the user model to access that element.

So the whole thing looks like:

View:

<%= text_field_tag :profile, params[:profile] %></p>

Controller:

@user.profile = params[:profile]

Model:

  attr_accessor :profile

After that I could access the profile element the same as the regular elements in the user model.


Try:

@user = User.new(params[:user])
@user.profile = Profile.new(params[:profile])

or

@user = User.new(params[:user])
@user.attributes = params[:profile]
0

精彩评论

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