Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby on Rails - updating multiple models from the one controller
    primarykey
    data
    text
    <p>I'm trying to get my head around saving to multiple models from the one controller and it's probably really simple but I can't figure it out.</p> <p>I have a User Model that has many <code>loanitems</code> and the <code>loanitems</code> belong to the user associations set up.</p> <p>In my <code>loanitems</code> controller I want each <code>loanitem</code> create action to update a the <code>user.points</code> </p> <p>So at the moment I have the following code that doesn't throw any errors but doesn't update the user model either.</p> <pre><code>def create @loanitem = current_user.loanitems.build(params[:loanitem]) respond_to do |format| if @loanitem.save @loanitem.user.points = @loanitem.user.points + 50 @loanitem.user.save format.html {redirect_to root_path, :flash =&gt; {:success =&gt; "Loan Item created" } } format.xml{render xml: root_path} else format.html {render 'pages/home' } format.xml {render xml: 'pages/home'} end end end </code></pre> <p>I'm also trying the following variation on a theme</p> <pre><code> def create @loanitem = current_user.loanitems.build(params[:loanitem]) respond_to do |format| if @loanitem.save current_user.points = current_user.points + 50 current_user.save format.html {redirect_to root_path, :flash =&gt; {:success =&gt; "Loan Item created" } } format.xml{render xml: root_path} else format.html {render 'pages/home' } format.xml {render xml: 'pages/home'} end end end </code></pre> <p>But should I be sending some message instead to the <code>userupdate</code> controller instead? That currently looks like this ...</p> <pre><code>def update @user = User.find(params[:id]) if @user.update_attributes(params[:user]) redirect_to @user, :flash =&gt; { :success =&gt; "Profile has been updated!"} else @title = "Edit Profile" render 'edit' end end </code></pre> <p>Or I have heard that the business logic really should all be contained in the model so maybe the method should be written in <code>User.rb</code> and then called by the <code>Loanitems</code> controllers create method? </p> <p>I know it's a real rookie question but any advice would be really welcome. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload