w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Ruby On Rails Pagination and delete :through association
The problem is the code to fetch the items @collection.items = Collection.find(params[:id]).items it assigned the fetched items to current collection object. you need to change the response to support the pagination on associate objects   def show    @collection = Collection.find(params[:id]) respond_to do |format| format.json { json_hash = @collection.as_json json_hash[:items] = @collection.items.paginate(:page => params[:page],:per_page =>1).as_json render json: json_hash.to_json } end Additionally you can overwrite to_json method inside Collection model.

Categories : Ruby On Rails

Rails - set default association on delete of has_many model
You can override your getter for profile association: def profile user.profile_id ? Profile.find(id) : user.default_profile end default_profile is your method that will return default profile. Also you can use alias_method: alias_method :original_profile, :profile def profile original_profile || user.default_profile end

Categories : Ruby On Rails

How do I test a has_many :through association that also has a validates_presence_of validation on the association with Factory Girl in Rails?
The error message says expected ..... to be valid, but got errors: Client can't be blank work = FactoryGirl.build(:work) # this returns an unsaved object By using build you haven't saved the object. The object is nil. If an object is nil it is blank You want to save the object on creation like this work = FactoryGirl.create(:work) # this returns a saved object Now work.should be_valid should pass UPDATE: I didn't look closely enough at your `factories.rb' factory :work do name "Client Website" client date 1.day.ago description "A great new website for the client." image "/image.jpg" service "Web" featured true end your client attribute in the work factory is literally blank. This wont pass validation and won

Categories : Ruby On Rails

hibernate delete many-to-many association
This is not a matter of cascade, because cascade means (in the DELETE case): "delete the target when you delete me". Try the orphanRemoval: public class Product { @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy="product", orphanRemoval=true) private Set<StoreProductLink> stores = new HashSet<StoreProductLink>();

Categories : Java

How to get an Id value from association rails
First you need to remove the attribute disabled from your field, a disabled field isn't sended by your form (look at Disabled form fields not submitting data). And, your user_id should be placed in something like params[:note][:user_id], take a look at server log and search for user_id right after you send a POST to server, there be something like: Started POST "/note" for ::1 at 2013-07-18 15:22:34 +0000 Processing by NoteController#create as */* Parameters: {"note"=>{..., "user_id"=>"1", ...}}

Categories : Ruby On Rails

Rails association
class Post has_one :photo, as: :photoable end class Project has_one :photo, as: :photoable end class Photo belongs_to :photoable, polymorphic: true end http://guides.rubyonrails.org/association_basics.html (check out section 2.9 on polymorphic associations)

Categories : Ruby On Rails

rails / bootstrap delete link issue: data-method delete not working
based on this answer Delete link sends "Get" instead of "Delete" in Rails 3 view I added <%= csrf_meta_tag %> in header, which fixed the issue

Categories : Ruby On Rails

Polymorphic association in Rails 3
You should have your association the other way round class Question < ActiveRecord::Base belongs_to :askable, :polymorphic => true end class TextProblem < ActiveRecord::Base has_many :questions, :as => :askable ... end class MultipleChoice < ActiveRecord::Base has_many :questions, :as => :askable ... end class WordMatch < ActiveRecord::Base has_many :questions, :as => :askable ... end Refer to this.

Categories : Ruby On Rails

Rails route for through association
resources :categories do resources :posts end Will give you the resources for /category/1/post/1 http://guides.rubyonrails.org/routing.html#nested-resources Have a look at this railscast for titles in the ulr EDIT: To answer your previous comment i would suggest you this: @category = Category.find(params[:id]) @posts = @category.posts

Categories : Ruby On Rails

Rails Association Chains
I don't think that Rails 2.3.14 supports the .where() - Actually it does not for Rails 2.3.11, just tried it. In Rails 2.3.14, you can't really chain the queries... Here is the Rails 2.3.x solution: @circuit.organisation.circuits.find(:all, :conditions => ['id != ?', @circuit.id])

Categories : Ruby On Rails

rails polymorphic many-to-many association
You could do the following Category.first.categorizables.where(categorizable_type: 'Company') that would select all the Companies associated with Category using your relationship schema. Also read some about has_many :through association because I think you don't quite get it http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

Categories : Ruby On Rails

Querying many-to-many association in Rails
physician.appointments.includes(:patients).each do |appointment| puts appointment.appointment_time puts appointment.patient.name end **This is not tested As far as I know the rails way you are looking for doesn't really exist. To make sure you are not loading each one on every loop you can use an includes. I am not sure if I am putting the includes in the right place because I do not have access to rails console at the moment. If there are a lot of records you may want to batch find using find_each but for your example this should work.

Categories : Ruby On Rails

Rails User Association with comments
first I would show the edit and destroy link only to owner with: <% if comment.user == current_user %> <%= link_to "edit", ... %> <%= link_to "delete", ... %> <% end %> and then just in case for smart guys who knows how to use inspect element in chrome, I would do a controller level check for comment owner: def edit @comment = Comment.find(params[:id]) if @comment.user == current_user @comment.update_attributes(....) @message = "Comment updated or created or deleted, depends on method" else @message = "It's not your comment wise guy :)" end redirect_to :back, notice: @message end the same for destroy and update method. !not a copy/paste ready code. this is what I did once and it worked quite nice, other method you can use gem cancan

Categories : Ruby On Rails

Which association to use in this has_many with three resources in Rails?
Use a has-many-through association: class Corporation has_many :companies end class Company belongs_to :corporation has_many :company_states has_many :states, through: :company_states end class CompanyState belongs_to :company belongs_to :state end class State has_many :company_states has_many :companies, through: :company_states end company = Company.new(name: 'foo', description: 'bar') state = State.find_by_name('MA') company.company_states << CompanyState.new(state: state, phone_number: '800-555-1212')

Categories : Ruby On Rails

How to query model with association in Rails?
Shouldn't be too tricky to debug .. open your rails console and stick in UserEvent.joins(:event_dates).where(event_dates: { user_event_date: 10.days.ago..DateTime.now }) ..or change the dates so that you know you will get some data returned. Check the data is correct. If that works then your problem is elsewhere. As for your other question, if you try and use nil in a range you'll get ArgumentError: bad value for range. So yes, depending on how you want it to behave, the usual solution is to check for nil values and replace it with something appropriate for the behaviour you'd like to implement. Edit - Oddly, nil..nil as a range doesn't produce an ArgumentError, which could mean that you're not setting the values successfully. How are you setting the values of user_event_date_from an

Categories : Ruby On Rails

Ruby on Rails Use Model Association
The problem lies in directly accessing the variables in the @user_answer object, and not updating the user_answer within the @user variable...and since Rails has an update method, we can do this like so: begin @user_answer = @user.user_answers.where(:question_id => @question_id).first if @user_answer @user.user_answers.update(:question_id => @question_id, :answer_id => @answer_id) @message = 'Answer updated successfully!' else @user.user_answers.create(:question_id => @question_id, :answer_id => @answer_id) @message = 'Answer submitted successfully!' end rescue ex @message = ex.message.split(':')[1].chomp end But we can do better. Rather than differ by create and update, we can simply use Ruby's short circuit evaluation to create a `@user_answer

Categories : Ruby On Rails

Rails Association, Scope, JoinModel
I would do it one of the following 2 ways, not for performance reasons, just for clarity of expression: Are there any manifests belonging to @assembly and @part? Manifest.where(assembly_id: @assembly.id, part_id: @part.id).any? Or, do @assembly and @part share any manifests? (@assembly.manifests & @part.manifests).any?

Categories : Ruby On Rails

Has_many through association with sub-groupings (Rails)
Ok, so what I think I would do is to create two models: Community and CommunityGroup, and then associate them with has_and_belongs_to_many or has_many :through dependent if you want to save any information on Community-Group relationship (probably not). It would be easy to quickly fetch all communities in a group, etc.

Categories : Ruby On Rails

Rails simple_form association issue
pass a label_method. like <%= f.association :team, label_method: "#{:city} #{:name}" %> better yet, you might already have the full_name functionality in place, just call that You might have to also use the value_method option and set to team_id to properly set it if simple_form can't properly guess form the passed in association

Categories : Ruby On Rails

Rails updating model through association
I don't this inverse_of works with has_many through. See this article: ActiveRecord :inverse_of does not work on has_many :through on the join model on create Here is the relevant blurb from the RailsGuides: There are a few limitations to inverse_of support: They do not work with :through associations. They do not work with :polymorphic associations. They do not work with :as associations. For belongs_to associations, has_many inverse associations are ignored.

Categories : Ruby On Rails

Rails inverse polymorphic association
For your pets example, STI may be a solution: class Person < ActiveRecord::Base has_many :pets end class Pet < ActiveRecord::Base belongs_to :owner, class_name: "Person", foreign_key: "person_id" # Be sure to include a :type attribute for STI to work end class Dog < Pet end class Cat < Pet end This should still give you access to @person.pets and @dog.owner, @pet.owner, etc.

Categories : Ruby On Rails

Getting has_many association from ngResource in rails
You can nest in Angular like this <li ng-repeat='event in events'> {{ event.name }} || <small>{{ event.date }}</small> <ul> <li ng-repeat='spike in event.spikes'> {{ spike.some_output_value }} </li> </ul> </li> You will, however need to ensure that the way you are passing the data to angular has already resolved the spike property of events. Hope this helps

Categories : Ruby On Rails

Please explain rails has_many through association
I feel the problem lies in the Distributors class name because it's plural. when you say something like has_many :distributors, Rails by default will link to the Distributor class, but in your case the class name is Distributors. Adding class_name option to your relationship declarations should work: class Product < ActiveRecord::Base has_one :product_distributor has_one :distributor, through: :product_distributor, class_name: 'Distributors' end class ProductDistributor < ActiveRecord::Base belongs_to :product belongs_to :distributor, class_name: 'Distributors' end class Distributors < ActiveRecord::Base has_many :product_distributors has_many :products, through: :product_distributors end Also note that your belongs_to should be singular not plural. Ple

Categories : Ruby On Rails

Rails migrate a column to an association
Here is how to generate a rake task in Rails: http://railsguides.net/2012/03/14/how-to-generate-rake-task/ Your rake task to update the historic records should look something like this: # lib/tasks/something.rake desc "Update old stuff" task :my_task1 => :environment do tickets = Ticket.where("purchase_id IS NULL") tickets.each do |ticket| ticket.purchase.create!([attributes]) ...[more stuff]... end end Run the rake task on the command like: $ bundle exec rake my_task1 I was not able to follow the logic of your application 100%, but hopefully this will set you in the right direction.

Categories : Ruby On Rails

Ruby on Rails four-way association tree
You're in the right track, but story and image shouldn't belong to user. You're creating a redundancy in there. class User < ActiveRecord::Base has_many :events has_many :stories, :through => :events has_many :images, :through => :events end class Event < ActiveRecord::Base belongs_to :user has_many :stories has_many :images end class Story < ActiveRecord::Base belongs_to :event end class Image < ActiveRecord::Base belongs_to :event end This way you can still write user.stories and user.images.

Categories : Ruby On Rails

Rails featured image association?
You can do what you want using a has_one :through association. class Post < ActiveRecord::Base has_and_belongs_to_many :images has_one :featured_image, :through => :feature, :class_name => 'Image' has_one :feature end class Image < ActiveRecord::Base has_and_belongs_to_many :images has_many :featured_images, :through => :features, :class_name => 'Image', :foreign_key => :featured_image_id has_many :features end class Feature < ActiveRecord::Base belongs_to :featured_image, :class_name => 'Image' belongs_to

Categories : Ruby On Rails

Rails association with custom fields
I would create the following: class User has_many :purchases end class Product has_many :purchases end class Purchase belongs_to :user belongs_to :product # mongoid syntax, if using ActiveRecord, use a migration field :quantity, type: Integer, default: 0 field :price, type: Float, default: 0.0 end user = User.new apple = Product.new tea = Product.new chocolate = Product.new user.purchases.build(product: apple, price: 2.99, quantity: 1) user.purchases.build(product: tea, price: 5.99, quantity: 2) user.purchases.build(product: chocolate, price: 3.99, quantity: 3) FYI: This kind of relations between User, Product and Purchase is similar to a has_and_belongs_to_many. When using the has_and_belongs_to_many, rails simply link the classes like above. Here we are doing it our

Categories : Ruby On Rails

Rails: get records for has_and_belongs_to_many association
Not sure what the brand association represents and posting your models would go a long way to help figure this out, but here's a guess: current_user.brand.articles.joins(:templates).where(:templates => { :id => @template.id }) You were pluralizing templates in the where clause but not in the join.

Categories : Ruby On Rails

N+1 query with rails polymorphic association
See if this answer applies for you Ruby on Rails: :include on a polymorphic association with submodels

Categories : Mysql

Relationship advice/association logic in rails
I think you might be thinking too far ahead. Once you have your app built around your current data model, you'll know better whether you even want to expand it to include the concept of a goal that isn't part of a student's subject. If you decide that it is, then making goals belong_to a subject, student, or user will be pretty simple. At that point, you could also do something like Class Student has_many :personal_goals, class_name: "Goal" has_many :goals, through: :subjects def all_goals goals + personal_goals end There's probably a more elegant way to model that last relationship. Would you need to go beyond that? Does it make sense to talk about a student group having a goal of its own? I don't know.

Categories : Ruby On Rails

Rails: ActiveRecord association won't work when specifying foreign key
I think you are asking for all of the students that have an institutionid of 433. However institutionid is not the primary key of School (and I wonder why not?). So when you say school.students, the query will use the value in 'id' not in 'institutionid'. I would try changing Student's association to: belongs_to :school, :foreign_key => :institutionid, :primary_key => :institutionid and change School to: has_many :students, :foreign_key => :institutionid, :primary_key => :institutionid

Categories : Ruby On Rails

Rails determine if association is has_one or has_many
UPDATE: So, I happened upon the Reflections Class methods http://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html You can get all the has_many, belongs_to, etc. with reflect_on_all_associations method. It's all in there. Or you can put in an association into reflect_on_association and it will tell you if it is a has_many, has_one, etc. Specifically: Model.reflect_on_association(:assoc).macro This should be sufficient for all cases. It doesn't actually solve the problem I'm currently working on, but it should solve this.

Categories : Ruby On Rails

Rails: Display object name using has_many :through association
Please using association relation table. %table %tr %th Publication %th User %th Created at - @publication.each do |publication| %tr %td= publication.thread.name %td= publication.user.username %td= publication.created_at

Categories : Ruby On Rails

Rails find all records with an association under certain conditions
In your User model, def self.no_salary_report User.all.select {|u| u.salary_reports.empty? } end To call it, User.no_salary_report This will get you all the users without any salary_reports. I don't exactly know your model names, so this is best I can do. edit 1: For time range you additionally asked def self.no_salary_reports_between(start_date, end_date) User.all.select do |u| u.salary_reports.select do |s| (start_date < s.created_at) && (end_date > s.created_at) end.empty? end end Note that start_date and end_date arguments you give to this method must be DateTime object to work correctly compare the value to the created_at values of salary_reports.

Categories : Ruby On Rails

Rails association skip update associated object
You can try something like this class City<ActiveRecord::Base has_one :template, class_name:'TmplLocation', :conditions => { :id => 18 } end For more options see this guides.rubyonrails.org

Categories : Ruby On Rails

How to persist data via has_many through association in rails
First you will have to find transaction_group record which you want to associate with transaction: transaction_group = batch.transaction_groups.find(id) #(or batch.transaction_groups.first for first record) Then you can create associated transaction record by: transaction_group.transactions.build or, batch.transactions.build(:transaction_group_id => transaction_group.id)

Categories : Ruby On Rails

can't seem to get rails association to limit columns with json
You should limit the elements by passing your parameters to the render method like this: render :json => items.to_json(:include => { :sizes => { :only => [:id, :name, :price] }} this should do it for you.

Categories : Ruby On Rails

Rails 3: validate presence of at least one has many through association item
Side note before the answer, based on the structure of your models I would use has_and_belongs_to_many instead of using this explicit linking model since it appears the linking model doesn't add anything of value. Either way though, the answer is the same, which is to use a custom validation. Depending on whether you go with things the way they are or simplify to a has_and_belongs_to many you'll want to validate slightly differently. validate :has_project_disciplines def has_project_disciplines errors.add(:base, 'must add at least one discipline') if self. project_disciplinizations.blank? end or with has_and_belongs_to_many validate :has_project_disciplines def has_project_disciplines errors.add(:base, 'must add at least one discipline') if self.project_disciplines.blank? end

Categories : Ruby On Rails

Rails has_many custom ActiveRecord Association
I think the best way would be to write an instance method for that: In the Team model: def games Fixture.where("home_id = ? OR away_id = ?", self.id, self.id) end Use it like a regular method: Team.first.games #=> [<Fixture id: ... >, <Fixture id: ... >, ... ] This should return an ActiveRecord::Relation which is re-usable for scope-chaining, etc. (Here is a similar question, but with has_one: Rails Model has_many with multiple foreign_keys) Also, you could make a class method from it using the id of the Team (if you already have the team_id but not the Team instance object): class Team < ActiveRecord::Base has_many :home_games, :class_name => 'Fixture', :foreign_key => 'home_id' has_many :away_games, :class_name => 'Fixture', :foreign_key =>

Categories : Ruby On Rails

undefined method `where' in ruby on rails association
If table2 belongs to table1, then calling table2.table1 will give you a single object of type table1. You can't call where on a single object (nor does it make sense to do so), only on a table or relation.

Categories : Ruby On Rails



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.